const Controller = require('egg').Controller
const fs = require('fs')
// node.js 路径操作对象
const path = require('path')
// egg.js Controller
const awaitWriteStream = require('await-stream-ready').write
// 管道读入一个虫洞。
const sendToWormhole = require('stream-wormhole')

class TaskController extends Controller {
    /* 前台 */
    async uploadTask() {
      const { ctx, config } = this
      const stream = await ctx.getFileStream();
      // 文件名:随机数+时间戳+原文件后缀
      // path.extname(stream.filename).toLocaleLowerCase()为后缀名（.jpg,.png等）
      const filename = Math.random().toString(36).substr(2) + new Date().getTime() + path.extname(stream.filename).toLocaleLowerCase();
      // 图片存放在静态资源public/img文件夹下
      const target = path.join(config.baseDir, 'app/public/task', filename);
      // 生成一个文件写入 文件流
      const writeStream = fs.createWriteStream(target);
      try {
        // 异步写入文件流
        await awaitWriteStream(stream.pipe(writeStream));
      } catch (err) {
        // 如果出现错误，关闭管道
        await sendToWormhole(stream);
        throw err;
      }
  
      ctx.body = {
        code: '0',
        filename: path.join('/public/task', filename),
        desc: '上传成功'
      };
    }
    //获取所有打卡数据
    async getTasks() {
      try {
        const { ctx, app } = this
        const { searchForm, page, limit } = ctx.request.body;
        let conditions = {}
        // 搜索
        if(!searchForm) {
        } else {
          if(!!searchForm.username) {
            conditions.sign_id = searchForm.username;
          }
          if(!!searchForm.finishWrite) {
            conditions.finish_write = searchForm.finishWrite;
          } 
          if(!!searchForm.phone) {
            conditions.finish_video = searchForm.finishVideo;
          }
        }
        const pageOffset = ctx.helper.toInt((page - 1) * limit);
        const pageLimit = ctx.helper.toInt(limit);
        const tasks = await ctx.model.Task.findAndCountAll({
          include:[{
            model: app.model.User,
            attributes:['id','username','avatar']
          }],
          where: conditions,
          limit: pageLimit,
          offset: pageOffset
        })
        ctx.body = {
          code: '0',
          detail: tasks.rows,
          count: tasks.count,
          desc: '打卡数据查询成功'
        }
      } catch(error) {
        const { ctx } = this
  
        ctx.body = {
          code: '-1',
          desc: '打卡数据查询失败',
          err: error
        }
      }
    }
    //获取用户当日打卡
    async getTask() {
      try {
        const { ctx, app } = this
        const { Op } = app.Sequelize
        const { userId } = ctx.request.body
        const START = new Date().setHours(0,0,0,0)
        const END = new Date().setHours(23,59,59,59)
        const detail = await ctx.model.Task.findAll({
          where: {
            sign_id: userId,
            created_at: {
              [Op.gte]: START,
              [Op.lte]: END
            }
          }
        })
  
        ctx.body = {
          code: '0',
          detail: detail,
          desc: '打卡数据查询成功'
        }
      } catch(error) {
        const { ctx } = this
  
        ctx.body = {
          code: '-1',
          desc: '打卡数据查询失败',
          err: error
        }
      }
    }
    //获取用户本周七天打卡情况
    async getWeekTasks() {
      try {
        const { ctx, app } = this
        const { Op } = app.Sequelize
        const { userId, startDate, endDate } = ctx.request.body
        const detail = await ctx.model.Task.findAll({
          where: {
            sign_id: userId,
            created_at: {
              [Op.gte]: startDate,
              [Op.lte]: endDate,
            }
          }
        })
        ctx.body = {
          code: '0',
          detail: detail,
          desc: '打卡数据查询成功'
        }
      } catch(error) {
        const { ctx } = this
        ctx.body = {
          code: '-1',
          desc: '打卡数据查询失败',
          err: error
        }
      }
    }
    //获取用户当月打卡情况
    async getMonthTasks() {
      try {
        const { ctx, app } = this
        const { Op } = app.Sequelize
        const { userId, year, month, lastDay } = ctx.request.body
        const startDate = year+'-'+month+'-1'
        const endDate = year+'-'+month+'-'+lastDay
        const detail = await ctx.model.Task.findAll({
          where: {
            sign_id: userId,
            created_at: {
              [Op.gte]: startDate,
              [Op.lte]: endDate
            }
          }
        })
        ctx.body = {
          code: '0',
          detail: detail,
          desc: '打卡数据查询成功'
        }
      } catch(error) {
        const { ctx } = this
        ctx.body = {
          code: '-1',
          desc: '打卡数据查询失败',
          err: error
        }
      }
    }
    //保存打卡
    async saveTask() {
      try {
        const { ctx } = this
        const { taskImages, finishWrite, finishVideo, userId } = ctx.request.body
        await ctx.model.Task.create({
          task_images: taskImages,
          finish_write: finishWrite,
          finish_video: finishVideo,
          sign_id: userId
        })
        ctx.body = {
          code: '0',
          desc: '打卡成功~'
        }
      } catch(error) {
        const { ctx } = this
        ctx.body = {
          code: '-1',
          desc: '打卡失败，请重试',
          err: error
        }
      }
    }
    //增加积分
    async addPoints() {
      try {
        const { ctx } = this
        const { points, userId } = ctx.request.body
        await ctx.model.User.update({
          points
        }, {
          where: {
            id: userId
          }
        })
        ctx.body = {
          code: '0',
          desc: '积分增加成功~'
        }
      } catch(error) {
        const { ctx } = this
        ctx.body = {
          code: '-1',
          desc: '积分增加失败，请重试',
          err: error
        }
      }
    }
}

module.exports = TaskController